// Register page module
// ====================

define(['zepto', 'wx', 'JST', 'page/jst/fitness-tag-bind', 'sui'], function($, wx, JST, tagBind) {
  return {
    init: function(data) {
      this.initPicker(data.groups, data.tags);

      this.groupSubmit(data.roundId);
      tagBind.init(data.tags)
    },
    
    initPicker: function(groups, tags) {
        
        var groupDisplay = new Array(),
            groupValue = new Array();
        $.each(groups, function(k, group) {
            groupDisplay[k] = group.name;
            groupValue[k] = group.id;
        })
        
        this.bindGroupSelectEvent(groupDisplay, groupValue);
        //this.bindTagSelectEvent(tagDisplay, tagValue);
    },
    
    groupSubmit: function(roundId) {
      
      $('.btn-group').click(function() {
        var groupId = $('input[name="groupId"]').val();
          var tagIds = $('input[name="tagId"]').val();
          if(!groupId) {
            $.toast("分组信息不可为空");
            return false;
          }
          
          $(this).parent(".group-submit").addClass("hide");
          
          $.ajax({
            url: window.__CTX__.root + '/rounds/' + roundId + '/group',
            type: 'POST',
            data: {
              '_method': 'PATCH',
              'groupId': groupId,
              'tagIds': tagIds
            },
            success: function(res) {
              var res = JSON.parse(res);
              $.toast(res.message);
              window.location.href = window.__CTX__.root + '/rounds?type=GROUPING'
            }
          })
      })
    },
    
    bindGroupSelectEvent: function(groupDisplay, groupValue) {
        $("#group-picker").picker({
            toolbarTemplate: '<header class="bar bar-nav">\
                                <button class="button button-link pull-right close-picker">确定</button>\
                                <h1 class="title">请选择分组</h1>\
                              </header>',
          cols: [{
              textAlign: 'center',
              values: groupValue,
              displayValues: groupDisplay
            }],
          formatValue: function (picker, value, displayValue){
              $(this.input).next().val(value)
              return displayValue
          },
        });
    }
  }
  
})